package net.weamor.interfaces.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/** 
 * @ClassName XmlUtil  
 * @Description xml及bean转换解析功能类 
 *   
 */
public class XmlKit {
	private static Logger logger = LoggerFactory.getLogger(XmlKit.class);
	/**
	 * @Title: getTomcatPath 
	 * @Description: 根据相对路径得到Tomcat运行绝对路径
	 * @param path
	 * @return String    返回类型
	 */
	public static String getTomcatPath(String path) {
		String nowPath;
		String tempPath;
		nowPath = System.getProperty("user.dir");
		tempPath = nowPath.replace("bin", "webapps");
		if(tempPath.contains("webapps")){
			tempPath += "/" + path;
		}else{
			tempPath += "/webapps/" + path;
		}
		return tempPath;
	}
	
	 /**
     * @Title: toBean 
     * @Description: 将传入xml文本转换成Java对象 
     * @param xmlStr xml文本
     * @param cls  xml对应的class类
     * @return T   xml对应的class类的实例对象
     */
	@SuppressWarnings("unchecked")
	public static <T> T  toBean(String xmlStr,Class<T> cls){
        XStream xstream=new XStream(new DomDriver());
        xstream.processAnnotations(cls);
        T obj=(T)xstream.fromXML(xmlStr);
        return obj;         
    } 
	
	/**
     * @Title: toBeanFromFile 
     * @Description: 读取xml文件转换成Java对象  
     * @param filePath 文件绝对路径
     * @param cls
     * @return T
     */
	@SuppressWarnings("unchecked")
    public static <T> T  toBeanFromFile(String filePath,Class<T> cls){
		InputStream ins = null ;
		T obj =null;
		try {
			ins = new FileInputStream(new File(filePath ));
			XStream xstream=new XStream(new DomDriver("UTF-8"));
	        xstream.processAnnotations(cls);
	        obj = (T)xstream.fromXML(ins);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("读"+ filePath +"文件失败！");
        } finally{
        	if(ins != null){
        		try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
        return obj;         
    } 
}
